#pragma once
#include <string.h>
#include <sys/epoll.h>
#include <unistd.h>
#include "log.hpp"
#include "common.hpp"

class Epoller
{
public:
    Epoller()
    {
        _epfd=epoll_create(128);
        if(_epfd<0)
        {
            Log(FATAL,"create epoll error:%s",strerror(errno));
            exit(CREATE_EPOLL_ERROR);
        }
        Log(DEBUG,"create epoll success");
    }

    ~Epoller()
    {
        if(_epfd>=0)
            ::close(_epfd);
    }

    bool AddEvent(int fd,uint32_t events)
    {
        struct epoll_event ev;
        ev.data.fd=fd;
        ev.events=events;
        int n=epoll_ctl(_epfd,EPOLL_CTL_ADD,fd,&ev);
        if(n<0)
        {
            Log(ERROR,"epoll ctl error",strerror(errno));
            return false;
        }
        Log(DEBUG,"epoll ctl add %d success",fd);
        return true;
    }

    int Wait(struct epoll_event events[],int gnum,int timeout)
    {
        int n=epoll_wait(_epfd,events,gnum,timeout);
        return n;
    }
private:
    int _epfd;
};